<template>
  <a-modal
    :title="title||'订单列表'"
    :width="1200"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    :footer="null"
    @ok="handleSubmit"
    @cancel="handleCancel">

    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline" v-show="false">
          <a-row :gutter="48">

            <a-col :md="8" :sm="24">
              <a-form-item label="订单号">
                <a-input v-model="queryParam.orderNumber" placeholder="请输入订单号"/>
              </a-form-item>
            </a-col>

            <a-col :md="8" :sm="24">
              <a-form-item label="源引订单Id">
                <a-input v-model="queryParam.sourceOrderId" placeholder="请输入源引订单Id"/>
              </a-form-item>
            </a-col>

            <a-col :md="8" :sm="24" v-show="$isDev">
              <!--            <a-input v-model="queryParam.orderType" placeholder="请输入订单类型"/>-->
              <a-form-item label="订单类型">
                <a-select default-value="" v-model="queryParam.orderType"
                          style="width: 120px">
                  <a-select-option :value="item.id" v-for="(item, index) in orderTypeList">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :md="8" :sm="24" v-show="$isDev">
              <a-form-item label="执行状态">
                <a-select default-value="" v-model="queryParam.executeStatus"
                          style="width: 120px">
                  <a-select-option :value="id" v-for="{id, name, code} in executeStatusList">
                    {{ name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :md="!advanced && 8 || 24" :sm="24">
            <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <!--<a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>-->
            </span>
            </a-col>

            <!--            <a-col :md="24" :sm="24">-->
            <!--              <a-form-item label="供应商：">-->
            <!--                <a-radio-group default-value="" button-style="solid" v-model="queryParam.orgIdSupplier">-->
            <!--                  <a-radio-button value="">-->
            <!--                    全部-->
            <!--                  </a-radio-button>-->
            <!--                  <a-radio-button :value="id" v-for="{id, name} in suppliers">-->
            <!--                    {{ name }}-->
            <!--                  </a-radio-button>-->
            <!--                </a-radio-group>-->
            <!--              </a-form-item>-->
            <!--            </a-col>-->

            <!--            <a-col :md="24" :sm="24">-->
            <!--              <a-form-item label="归属公司：">-->
            <!--                <a-radio-group default-value="" button-style="solid" v-model="queryParam.orgIdCompany">-->
            <!--                  <a-radio-button value="">-->
            <!--                    全部-->
            <!--                  </a-radio-button>-->
            <!--                  <a-radio-button :value="id" v-for="{id, name} in orgs">-->
            <!--                    {{ name }}-->
            <!--                  </a-radio-button>-->
            <!--                </a-radio-group>-->

            <!--              </a-form-item>-->
            <!--            </a-col>-->

          </a-row>
        </a-form>
      </div>

      <s-table
        ref="table"
        size="default"
        :columns="columnsDynamic1"
        :data="loadData"
        :alert="true"
        :showPagination="false"
        :rowKey="(record) => record.code"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      >

      <span slot="status" slot-scope="text, record">
           <a-switch v-model:checked="record.status == 0" :loading="record.loading" @change="onOrderStatusChange($event, record)"/>
      </span>

        <span slot="actionCommon" slot-scope="text, record">
          <a @click="$refs.orderMaterialIndexModal.show(record,
          {title:'订单明细', viewState:'orderMaterialCommon', materialType})">订单明细</a>
        </span>

        <span slot="actionOutOrder" slot-scope="text, record">
        <!--    出库单明细 单独的按钮      -->
          <a @click="$refs.outOrderDetailForm.show(record,
          '出库明细',
          '',
          {'orderId':record.orderId})">订单明细</a>
        </span>

      </s-table>

      <!--  关联物料页面  -->
      <order-material-index-modal ref="orderMaterialIndexModal" @ok="handleOk"/>

<!--   出库单明细页   -->
      <out-order-detail-form ref="outOrderDetailForm"/>
    </a-card>
  </a-modal>
</template>

<script>
import {STable} from '@/components'
import {page, changeStatus, del, doScheduleProduction, doRecommendedProduction, doMaterialCalculation} from '@/api/modular/main/emsorder/emsOrderManage'
import {list as emsOrgList} from '@/api/modular/main/emsorg/emsOrgManage'
import {add} from '@/api/modular/main/emsbom/emsBomManage'
import {getUrlParam} from '@/utils/util'

import addForm from './emsOrderAddForm'
import editForm from './emsOrderEditForm'
import materialCalculationForm from './emsOrderMaterialCalculationForm'
import orderMaterialForm from './emsOrderMaterialIndexForm'

import deliverAddForm from '../emsordermaterial/deliverOrder/emsDeliverAddForm'
import productionOrderOutForm from '@/views/main/emsordermaterial/emsOrderMaterialProductionOrderOutForm'
import productCompleteForm from '@/views/main/emsordermaterial/emsOrderMaterialProductCompleteForm'
import inStoreForm from '@/views/main/emsordermaterial/emsOrderMaterialInStoreForm'
import outOrderDetailForm from '@/views/main/emsordermaterial/outOrder/emsOutOrderDetailForm'

export default {
  components: {
    STable,
    addForm,
    editForm,
    orderMaterialForm,
    deliverAddForm,
    materialCalculationForm,
    productionOrderOutForm,
    productCompleteForm,
    inStoreForm,
    // 为了解决与该控件的循环引用,所以使用如下方法
    orderMaterialIndexModal: () => import('@/views/main/emsordermaterial/emsOrderMaterialIndexModal'),
    outOrderDetailForm,
  },
  data() {
    return {
      visible: false,
      title: '',
      confirmLoading: false,
      advanced: false, // 高级搜索 展开/关闭
      queryParam: {},  // 查询参数
      columns: [       // 表头
        {
          title: '订单号',
          dataIndex: 'orderNumber'
        },
        {
          title: '订单类型',
          dataIndex: 'orderTypeStr'
        },
        {
          title: '是否可用',
          dataIndex: 'status',
          scopedSlots: {customRender: 'status'}
        },
        {
          title: '进度状态',
          dataIndex: 'executeStatusStr'
        },
        {
          title: '创建时间',
          dataIndex: 'createTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: {customRender: 'action'}
        }
      ],
      columnsInProduction: [
        {
          title: '序号', width:'80px',
          customRender: (text, record, index) => `${index + 1}`
        },
        {
          title: '生产单号',
          dataIndex: 'orderNumber'
        },
        {
          title: '归属子公司',
          dataIndex: 'orderTypeStr'
        },
        {
          title: '录入时间',
          dataIndex: 'createTime'
        },
        {
          title: '排单时间',
          dataIndex: 'createTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '250px',
          scopedSlots: {customRender: 'actionInProduction'}
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        // let ot = this.orderType
        // TODO 在搜索订单时有一种情况,需要搜索订单中的物料有被源引的订单.但由于一个订单在创建时可以对
        //  多个订单内容进行源引,所以导致这个有点麻烦.这个要么由接口提供支持,要么就需要修改订单表让它支
        //  持保存多个源引的订单ID!!!急要
        return page(Object.assign(parameter, this.queryParam)).then((res) => {
          return res.data
        })
      },
      scheduleProductionVisible: false,
      selectedRowKeys: [],
      selectedRows: [],
      defaultExpandedKeys: [],
      replaceFields: {
        key: 'id',
      },
      urlParam: {},
      columnsType: '',
      suppliers: [],
      orgs: [],
      emsOrder: {},
      viewState: '',
      materialType: '',
      extra: null,
    }
  },
  computed: {
    orderType() {
      return this.urlParam.orderType
    },
    ORDER_TYPE_ENUM() {
      return this.$businessEnum.ORDER_TYPE_ENUM
    },
    MATERIAL_TYPE_ENUM() {
      return this.$businessEnum.MATERIAL_TYPE_ENUM
    },
    orderTypeList() {
      let result = []
      result.push({id: '', name: '全部', code: 'all'})
      for (const key in this.$businessEnum.ORDER_TYPE_ENUM) {
        let value = this.$businessEnum.ORDER_TYPE_ENUM[key]
        result.push(value)
      }
      return result
    },
    executeStatus() {
      return this.urlParam.executeStatus
    },
    executeStatusList() {
      let result = []
      result.push({id: '', name: '全部', code: 'all'})
      for (const key in this.$businessEnum.EXECUTE_STATUS_ENUM) {
        let value = this.$businessEnum.EXECUTE_STATUS_ENUM[key]
        result.push(value)
      }
      return result
    },
    columnsDynamic1() {
      if (this.viewState == 'waitInStorePurchaseOrder') {
        // 待入库采购单
        return [
          {
            title: '序号', width:'80px',
            customRender: (text, record, index) => `${index + 1}`
          },
          {
            title: '采购单号',
            dataIndex: 'orderNumber'
          },
          {
            title: '总数量',
            dataIndex: ''
          },
          {
            title: '实到数量',
            dataIndex: ''
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: '250px',
            scopedSlots: {customRender: 'actionWaitInStorePurchaseOrder'}
          }
        ]
      } else if (this.viewState == 'alreadyInStorePurchaseOrder') {
        // 已入库采购单
        return [
          {
            title: '序号', width:'80px',
            customRender: (text, record, index) => `${index + 1}`
          },
          {
            title: '采购单号',
            dataIndex: 'orderNumber'
          },
          {
            title: '总数量',
            dataIndex: ''
          },
          {
            title: '实到数量',
            dataIndex: ''
          },
          {
            title: '采购开始时间',
            dataIndex: 'createTime'
          },
          {
            title: '入库完成时间',
            dataIndex: ''
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: '250px',
            scopedSlots: {customRender: 'actionAlreadyInStorePurchaseOrder'}
          }
        ]
      } else if (this.viewState == 'waitCompleteInStoreOrder') {
        // 入库单待完成
        return [
          {
            title: '序号', width:'80px',
            customRender: (text, record, index) => `${index + 1}`
          },
          {
            title: '发货单号',
            dataIndex: 'orderNumber'
          },
          {
            title: '总数量',
            dataIndex: ''
          },
          {
            title: '状态',
            dataIndex: 'status'
          },
          {
            title: '发货时间',
            dataIndex: 'createTime'
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: '250px',
            scopedSlots: {customRender: 'actionInStore'}
          }
        ]
      } else if (this.viewState == 'alreadyCompletedInStoreOrder') {
        // 入库单已完成(针对发货单的入库操作)
        return [
          {
            title: '序号', width:'80px',
            customRender: (text, record, index) => `${index + 1}`
          },
          {
            title: '发货单号',
            dataIndex: 'orderNumber'
          },
          {
            title: '总数量',
            dataIndex: ''
          },
          {
            title: '状态',
            dataIndex: 'status'
          },
          {
            title: '发货时间',
            dataIndex: 'createTime'
          },
          {
            title: '入库时间',
            dataIndex: ''
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: '250px',
            scopedSlots: {customRender: 'actionInStore'}
          }
        ]
      } else if (this.viewState == 'waitOutProductionOrder') {
        // 生产单待出库单(待调配物料的生产单)
        return [
          {
            title: '序号', width:'80px',
            customRender: (text, record, index) => `${index + 1}`
          },
          {
            title: '生产单号',
            dataIndex: 'orderNumber'
          },
          {
            title: '物料总数量',
            dataIndex: ''
          },
          {
            title: '出库数量',
            dataIndex: ''
          },
          {
            title: '开始时间',
            dataIndex: 'createTime'
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: '250px',
            scopedSlots: {customRender: 'actionOutMaterialToProductionOrder'}
          }
        ]
      } else if (this.viewState == 'alreadyOutProductionOrder') {
        // 生产单已出库单(已经调配完物料的生产单)
        return [
          {
            title: '序号', width:'80px',
            customRender: (text, record, index) => `${index + 1}`
          },
          {
            title: '生产单号',
            dataIndex: 'orderNumber'
          },
          {
            title: '开始时间',
            dataIndex: 'createTime'
          },
          {
            title: '结束时间',
            dataIndex: ''
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: '250px',
            scopedSlots: {customRender: 'actionOutMaterialDetailToProductionOrder'}
          }
        ]
      } else if (this.viewState == 'materialOutOrderByProductionOrder') {
        // 出库记录单(在生产单过程中因操作而创建的出库单记录,所以它不应叫出库单,而应该叫生产调配单)
        return [
          {
            title: '序号', width:'80px',
            customRender: (text, record, index) => `${index + 1}`
          },
          {
            title: '出库单号',
            dataIndex: 'orderNumber'
          },
          {
            title: '生产单号',
            dataIndex: 'orderNumber'
          },
          {
            title: '出库时间',
            dataIndex: 'createTime'
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: '250px',
            scopedSlots: {customRender: 'actionOutMaterialDetailToProductionOrder'}
          }
        ]
      } else if (this.viewState == 'materialSimpleOutOrder') {
        // 无单出库单(普通的物料出库单)
        return [
          {
            title: '序号', width:'80px',
            customRender: (text, record, index) => `${index + 1}`
          },
          {
            title: '出库单号',
            dataIndex: 'orderNumber'
          },
          {
            title: '物料总数量',
            dataIndex: 'orderNumber'
          },
          {
            title: '出库时间',
            dataIndex: 'createTime'
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: '250px',
            scopedSlots: {customRender: 'actionOutMaterialDetailToProductionOrder'}
          }
        ]
      } else if (this.viewState == 'outOrder') {
        // 生产单已出库 > [出库明细]  展示出库订单
        return [
          {
            title: '序号', width:'80px',
            customRender: (text, record, index) => `${index + 1}`
          },
          {
            title: '单号',
            dataIndex: 'orderNumber'
          },
          {
            title: '订单类型',
            dataIndex: 'orderType',
            customRender: (text, record, index) => {
              for (const key in this.$businessEnum.ORDER_TYPE_ENUM) {
                let otEnum = this.$businessEnum.ORDER_TYPE_ENUM[key];
                if (otEnum.id == text) {
                  return otEnum.name
                }
              }
              return '未知类型'
            }
          },
          {
            title: '创建时间',
            dataIndex: 'createTime'
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: '150px',
            scopedSlots: {customRender: 'actionOutOrder'}
          }
        ]
      } else if (this.viewState == 'materialSimpleInOrder') {
        // 无单入库单(普通的物料入库单)
        return [
          {
            title: '序号', width:'80px',
            customRender: (text, record, index) => `${index + 1}`
          },
          {
            title: '入库单号',
            dataIndex: 'orderNumber'
          },
          {
            title: '数量',
            dataIndex: 'orderNumber'
          },
          {
            title: '入库时间',
            dataIndex: 'createTime'
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: '250px',
            scopedSlots: {customRender: 'actionInMaterialDetailToProductionOrder'}
          }
        ]
      } else {
        return [
          {
            title: '序号', width:'80px',
            customRender: (text, record, index) => `${index + 1}`
          },
          {
            title: '单号',
            dataIndex: 'orderNumber'
          },
          {
            title: '订单类型',
            dataIndex: 'orderType',
            customRender: (text, record, index) => {
              for (const key in this.$businessEnum.ORDER_TYPE_ENUM) {
                let otEnum = this.$businessEnum.ORDER_TYPE_ENUM[key]
                if (otEnum.id == text) {
                  return otEnum.name
                }
              }
              return '未知类型'
            }
          },
          {
            title: '创建时间',
            dataIndex: 'createTime'
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: '150px',
            scopedSlots: {customRender: 'actionCommon'}
          }
        ]
      }
    }
  },
  created() {
    this.getSuppliers()
    this.getOrgs()
  },
  methods: {
    show(record, title, viewState, extra) {
      this.visible = true
      this.emsOrder = record
      this.title = title
      this.viewState = viewState
      this.queryParam.sourceOrderId = record.orderId
      if (record.orderMaterials) {
        // 如果前一个页面要求查询订单时需要筛选出物料源引的数据，则添加筛选条件
        this.queryParam.orderMaterials = record.orderMaterials
      }
      if (record.sourceOrderMaterialIds) {
        // 如果前一个页面要求查询订单时需要筛选出物料源引的数据，则添加筛选条件
        this.queryParam.sourceOrderMaterialIds = record.sourceOrderMaterialIds
      }
      this.queryParam.pageSize = -1
      if (extra) {
        this.extra = extra
        this.queryParam = Object.assign(this.queryParam, extra)
      }
      setTimeout(() => {
        this.handleOk()
      }, 100)
    },
    del(record) {
      del(record).then((res) => {
        if (res.success) {
          this.$message.success('删除成功')
          this.$refs.table.refresh()
        } else {
          this.$message.error('删除失败：' + res.message)
        }
      }).catch((err) => {
        this.$message.error('删除错误：' + err.message)
      })
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    handleSubmit() {
      this.visible = false
    },
    handleCancel() {
      this.visible = false
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    onOrderStatusChange(checked, row) {
      row.loading = true
      let {orderId} = row
      let status = checked ? 0 : 1
      let parameter = {orderId, status}
      changeStatus(parameter).then(res => {
        this.handleOk()
      })
    },
    // 排单生产
    handleScheduleProductionShow() {
      if (this.validateScheduleProduction()) {
        this.scheduleProductionVisible = true
      }
    },
    validateScheduleProduction() {
      let selectedRows = this.selectedRows
      if (selectedRows.length == 0) {
        this.$message.error('请先选择要排单生产的订单')
        return false
      }
      let unavailableOrders = selectedRows.filter(value => value.status != 0)
      if (unavailableOrders.length > 0) {
        this.$message.error('订单状态必须为"可用"才可以进行排单')
        return false
      }
      return true
    },
    handleOkByScheduleProduction() {
      // 调接口,排单生产
      if (this.validateScheduleProduction()) {
        let orderIds = this.selectedRows.map(value => value.orderId).join(',')
        doScheduleProduction({orderIds}).then(res => {
          this.$message.success(res.message)
        })
      }
    },
    handleRecommendedProduction() {
      // 推荐生产
    },
    handleMaterialCalculation() {
      // 物料计算
      let orderIds = this.selectedRows.map(row => row.orderId).join(',')
      this.$refs.materialCalculationForm.add(orderIds)
      // doMaterialCalculation({orderIds: selectedRowKeys}).then((res) => {
      //   let data = res.data
      //
      // })
    },
    getSuppliers() {
      emsOrgList({pid: '1473297518794452994', unitRanId: this.$businessEnum.ORG_TYPE_ENUM.PRIMARY_SUPPLIER.id}).then((res) => {
        this.suppliers = res.data
      })
    },
    getOrgs() {
      emsOrgList({pid: '1473297518794452994', unitRanId: this.$businessEnum.ORG_TYPE_ENUM.COMPANY.id}).then((res) => {
        this.orgs = res.data
      })
    }
  }
}
</script>

<style lang="less">
.table-operator {
  margin-bottom: 18px;
}

button {
  margin-right: 8px;
}
</style>
